﻿using MesProjectWinform.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace MesProjectWinform.Public.Common
{
    public class HttpClientHelper
    {
        public async static Task<string> RequestUrl(RequestType method, string url, string data)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 设置基础地址
                    client.BaseAddress = new Uri(Settings.Default.BaseUrl);
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);

                    Console.WriteLine($"请求URL: {client.BaseAddress}{url}");
                    Console.WriteLine($"请求方法: {method}");

                    HttpResponseMessage response = null; // 响应对象
                    HttpContent httpContent = null; // 请求内容

                    switch (method)
                    {
                        case RequestType.Get:
                            response = await client.GetAsync(url); // 发送GET请求
                            break;
                        case RequestType.Post:
                            httpContent = new StringContent(data, Encoding.UTF8, "application/json"); // 创建请求内容
                            response = await client.PostAsync(url, httpContent); // 发送POST请求
                            break;
                        case RequestType.Put:
                            httpContent = new StringContent(data, Encoding.UTF8, "application/json"); // 创建请求内容
                            response = await client.PutAsync(url, httpContent); // 发送PUT请求
                            break;
                        case RequestType.Delete:
                            response = await client.DeleteAsync(url); // 发送DELETE请求
                            break;
                        default:
                            break;
                    }

                    // 确保HTTP请求成功
                    if (response != null)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"HTTP响应状态码: {response.StatusCode}");

                        if (response.IsSuccessStatusCode)
                        {
                            return responseContent; // 返回响应内容
                        }
                        else
                        {
                            Console.WriteLine($"HTTP请求失败: {response.StatusCode}, 响应内容: {responseContent}");
                            return responseContent; // 即使失败也返回响应内容，让调用者处理错误
                        }
                    }

                    return string.Empty; // 如果响应为null
                }
            }
            catch (Exception ex)
            {
                // 记录异常
                Console.WriteLine($"HTTP请求异常: {ex.Message}");
                // 可以在这里添加更详细的日志记录

                // 返回空字符串，让调用者处理错误
                return string.Empty;
            }
        }


        public string RequestUrlNew(RequestType method, string url, string data, int timeoutSeconds = 30, Dictionary<string, string> headers = null)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 设置基础地址
                    client.BaseAddress = new Uri(Settings.Default.BaseUrl);
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
                    
                    // 添加自定义请求头
                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }

                    Console.WriteLine($"请求URL: {client.BaseAddress}{url}");
                    Console.WriteLine($"请求方法: {method}");

                    HttpResponseMessage response = null; // 响应对象
                    HttpContent httpContent = null; // 请求内容

                    // 创建请求内容
                    if (!string.IsNullOrEmpty(data) && (method == RequestType.Post || method == RequestType.Put))
                    {
                        httpContent = new StringContent(data, Encoding.UTF8, "application/json");
                    }

                    // 使用同步方式发送请求
                    switch (method)
                    {
                        case RequestType.Get:
                            response = client.GetAsync(url).ConfigureAwait(false).GetAwaiter().GetResult();
                            break;
                        case RequestType.Post:
                            response = client.PostAsync(url, httpContent).ConfigureAwait(false).GetAwaiter().GetResult();
                            break;
                        case RequestType.Put:
                            response = client.PutAsync(url, httpContent).ConfigureAwait(false).GetAwaiter().GetResult();
                            break;
                        case RequestType.Delete:
                            response = client.DeleteAsync(url).ConfigureAwait(false).GetAwaiter().GetResult();
                            break;
                        default:
                            throw new ArgumentException($"不支持的请求方法: {method}");
                    }

                    // 处理响应
                    if (response != null)
                    {
                        string responseContent = response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                        Console.WriteLine($"HTTP响应状态码: {response.StatusCode}");

                        // 返回响应内容，无论成功或失败
                        if (!response.IsSuccessStatusCode)
                        {
                            Console.WriteLine($"HTTP请求失败: {response.StatusCode}, 响应内容: {responseContent}");
                        }
                        
                        return responseContent;
                    }

                    return string.Empty;
                }
            }
            catch (HttpRequestException ex)
            {
                // 网络或服务器错误
                Console.WriteLine($"HTTP请求网络异常: {ex.Message}");
                return string.Empty;
            }
            catch (TaskCanceledException ex)
            {
                // 请求超时
                Console.WriteLine($"HTTP请求超时: {ex.Message}");
                return string.Empty;
            }
            catch (Exception ex)
            {
                // 其他异常
                Console.WriteLine($"HTTP请求异常: {ex.Message}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {ex.InnerException.Message}");
                }
                return string.Empty;
            }
        }
    }
}
